using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Threading;
using System.Windows;
using System.Windows.Threading;

namespace Rhizome.QuickStart.Elevator.ViewModel
{
    public abstract class ViewModelBase<TModel> : DependencyObject, INotifyPropertyChanged
        where TModel : class, INotifyPropertyChanged 
    {
        private TModel _model;
        public virtual TModel Model
        {
            [DebuggerStepThrough]
            protected get { return _model; }
            set
            {
                if (_model == value) return;
                _model = value;
                _model.PropertyChanged += ModelOnPropertyChanged;
            }
        }

        private void ModelOnPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (GetType().GetProperty(e.PropertyName) == null) return;

#if SILVERLIGHT || WINDOWS_PHONE
            if (CheckAccess()) InvokePropertyChanged(e.PropertyName);
            else Dispatcher.BeginInvoke(() => InvokePropertyChanged(e.PropertyName));
#else
            InvokePropertyChanged(e.PropertyName);
#endif
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void InvokePropertyChanged(string propertyName)
        {
            var handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}